<?php
/*
* 方倍工作室 http://www.fangbei.org/
* CopyRight 2015 All Rights Reserved
*/
define ( "TOKEN", "weixin" );

$wechatObj = new wechatCallbackapiTest ();
if (! isset ( $_GET ['echostr'] )) {
$wechatObj->responseMsg ();
} else {
$wechatObj->valid ();
}
class wechatCallbackapiTest {
// 验证签名
public function valid() {
	$echoStr = $_GET ["echostr"];
	$signature = $_GET ["signature"];
	$timestamp = $_GET ["timestamp"];
	$nonce = $_GET ["nonce"];
	$token = TOKEN;
	$tmpArr = array (
			$token,
			$timestamp,
			$nonce 
	);
	sort ( $tmpArr, SORT_STRING );
	$tmpStr = implode ( $tmpArr );
	$tmpStr = sha1 ( $tmpStr );
	if ($tmpStr == $signature) {
		echo $echoStr;
		exit ();
	}
}

// 响应消息
public function responseMsg() {
	$postStr = $GLOBALS ["HTTP_RAW_POST_DATA"];
	if (! empty ( $postStr )) {
		$this->logger ( "R \r\n" . $postStr );
		$postObj = simplexml_load_string ( $postStr, 'SimpleXMLElement', LIBXML_NOCDATA );
		$RX_TYPE = trim ( $postObj->MsgType );
		
		if (($postObj->MsgType == "event") && ($postObj->Event == "subscribe" || $postObj->Event == "unsubscribe")) {
			// 过滤关注和取消关注事件
		} else {
		}
		
		// 消息类型分离
		switch ($RX_TYPE) {
			case "event" :
				$result = $this->receiveEvent ( $postObj );
				break;
			case "text" :
				if (strstr ( $postObj->Content, "第三方" )) {
					$result = $this->relayPart3 ( "http://www.fangbei.org/test.php" . '?' . $_SERVER ['QUERY_STRING'], $postStr );
				} else {
					$result = $this->receiveText ( $postObj );
				}
				break;
			case "image" :
				$result = $this->receiveImage ( $postObj );
				break;
			case "location" :
				$result = $this->receiveLocation ( $postObj );
				break;
			case "voice" :
				$result = $this->receiveVoice ( $postObj );
				break;
			case "video" :
				$result = $this->receiveVideo ( $postObj );
				break;
			case "link" :
				$result = $this->receiveLink ( $postObj );
				break;
			default :
				$result = "unknown msg type: " . $RX_TYPE;
				break;
		}
		$this->logger ( "T \r\n" . $result );
		echo $result;
	} else {
		echo "";
		exit ();
	}
}

// 接收事件消息
private function receiveEvent($object) {
	$content = "";
	switch ($object->Event) {
		case "subscribe" :
			$content = "/:,@-D/:,@-D/:,@-D欢迎关注武纺新生助手！想查看更多功能请回复‘帮助’。";
			$content .= (! empty ( $object->EventKey )) ? ("\n来自二维码场景 " . str_replace ( "qrscene_", "", $object->EventKey )) : "";
			break;
		case "unsubscribe" :
			$content = "取消关注";
			$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
			mysqli_select_db ( $link, "app_formtest1" );
			mysqli_query ( $link, "UPDATE weixin_students SET student_weixin_id = 'NULL' WHERE student_weixin_id='$object->FromUserName'" );
			break;
		case "CLICK" :
			switch ($object->EventKey) {
				case '绑定通知书' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $object->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $object->FromUserName) {
						$content = "你已经绑定,不能重复绑定！";
					} else {
						$content [] = array (
								"Title" => "您还没有绑定，请点击绑定",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/band.jpg",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				case '个人信息' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $object->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $object->FromUserName) {
						$content [] = array (
								"Title" => "个人信息",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/gerenxinxi.jpg",
								"Url" => "http://8.formtest1.sinaapp.com/callback2.php" 
						);
					} else {
						$content [] = array (
								"Title" => "查看个人信息请先绑定",
								"Description" => "",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				case '学校简介' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $obj->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $obj->FromUserName) {
						$content [] = array (
								"Title" => "学校简介",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/xuexiaojianjie.jpg",
								
								// "Url"=>"http://wuhanfangzhida.flzhan.com"
								"Url" => "http://v.xiumi.us/board/v5/20M0G/5313136" 
						);
					} else {
						$content [] = array (
								"Title" => "查看学校简介请先绑定",
								"Description" => "",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				case '学院简介' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $obj->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $obj->FromUserName) {
						$content [] = array (
								"Title" => "学院简介",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/xueyuanjianjie.jpg",
								"Url" => "http://8.formtest1.sinaapp.com/callback.php" 
						);
					} else {
						$content [] = array (
								"Title" => "查看学院简介请先绑定",
								"Description" => "",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				case '校园导航' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $obj->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $obj->FromUserName) {
						$content = array ();
						$content [] = array (
								"Title" => "校园导航",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/xiaoyuandaohang.jpg",
								
								// "Url"=>"http://map.baidu.com/mobile/"
								"Url" => "http://1.formtest1.sinaapp.com/map2.php" 
						);
						
						$content [] = array (
								"Title" => "查询地图",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/mapchaxun.jpg",
								
								// "Url"=>"http://map.baidu.com/mobile/"
								"Url" => "http://map.baidu.com/mobile/webapp/index/index/foo=bar/tab=line" 
						);
						$content [] = array (
								"Title" => "查询公交",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/buschaxun.jpg",
								
								// "Url"=>"http://map.baidu.com/mobile/"
								"Url" => "http://map.baidu.com/mobile/webapp/third/transit/" 
						);
					} else {
						$content [] = array (
								"Title" => "查看校园导航请先绑定",
								"Description" => "",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				case '入学路线指南' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $obj->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $obj->FromUserName) {
						$content [] = array (
								"Title" => "入学路线指南",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/ruxueluxian.jpg",
								"Url" => "http://8.formtest1.sinaapp.com/route.php" 
						);
					} else {
						$content [] = array (
								"Title" => "查看入学路线指南请先绑定",
								"Description" => "",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				case '校园社区' :
					$kv = new SaeKV ();
					$ret = $kv->init ();
					$key = $obj->FromUserName;
					$myinfo_inkvdb = $kv->get ( $key );
					$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
					mysqli_select_db ( $link, "app_formtest1" );
					$sql = "select * from weixin_students where student_name='$myinfo_inkvdb'";
					$r = mysqli_query ( $link, $sql );
					$row = mysqli_fetch_object ( $r );
					$student_weixin_id = $row->student_weixin_id;
					if ($student_weixin_id == $obj->FromUserName) {
						$content [] = array (
								"Title" => "校园社区",
								"Description" => "",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/xiaoyuanshequ.jpg",
								"Url" => "http://8.formtest1.sinaapp.com/bbs/test.php" 
						);
					} else {
						$content [] = array (
								"Title" => "您还没有绑定，请点击绑定",
								"Description" => "this is a test",
								"PicUrl" => "http://8.formtest1.sinaapp.com/img/band.jpg",
								"Url" => "http://8.formtest1.sinaapp.com/callback1.php" 
						);
					}
					break;
				default :
					$content = "点击菜单：" . $object->EventKey;
					break;
			}
			break;
		case "VIEW" :
			$content = "跳转链接 " . $object->EventKey;
			break;
		case "SCAN" :
			$content = "扫描场景 " . $object->EventKey;
			break;
		case "LOCATION" :
			//$content = "上传位置：纬度 " . $object->Latitude . ";经度 " . $object->Longitude;
			break;
		case "scancode_waitmsg" :
			if ($object->ScanCodeInfo->ScanType == "qrcode") {
				$content = "扫码带提示：类型 二维码 结果：" . $object->ScanCodeInfo->ScanResult;
			} else if ($object->ScanCodeInfo->ScanType == "barcode") {
				$codeinfo = explode ( ",", strval ( $object->ScanCodeInfo->ScanResult ) );
				$codeValue = $codeinfo [1];
				$content = "扫码带提示：类型 条形码 结果：" . $codeValue;
			} else {
				$content = "扫码带提示：类型 " . $object->ScanCodeInfo->ScanType . " 结果：" . $object->ScanCodeInfo->ScanResult;
			}
			break;
		case "scancode_push" :
			$content = "扫码推事件";
			break;
		case "pic_sysphoto" :
			$content = "系统拍照";
			break;
		case "pic_weixin" :
			$content = "相册发图：数量 " . $object->SendPicsInfo->Count;
			break;
		case "pic_photo_or_album" :
			$content = "拍照或者相册：数量 " . $object->SendPicsInfo->Count;
			break;
		case "location_select" :
			$content = "发送位置：标签 " . $object->SendLocationInfo->Label;
			break;
		default :
			$content = "receive a new event: " . $object->Event;
			break;
	}
	
	if (is_array ( $content )) {
		if (isset ( $content [0] ['PicUrl'] )) {
			$result = $this->transmitNews ( $object, $content );
		} else if (isset ( $content ['MusicUrl'] )) {
			$result = $this->transmitMusic ( $object, $content );
		}
	} else {
		$result = $this->transmitText ( $object, $content );
	}
	return $result;
}

// 接收文本消息
private function receiveText($object) {
	$mem = memcache_init ();
	$keyword = trim ( $object->Content );
	// 多客服人工回复模式
	if (strstr ( $keyword, "请问在吗" ) || strstr ( $keyword, "在线客服" )) {
		$result = $this->transmitService ( $object );
		return $result;
	}
	
	// 自动回复模式
	if (strstr ( $keyword, "帮助" )) {
		$content = "回复1或者绑定：绑定通知书;\n回复2或者个人信息: 查看个人信息;\n回复城市名加天气可以查询天气;\n发送图片可以人脸识别;\n若要查询附近请先发送位置给我！\n点击底部的‘+’号，再选择‘位置’，等地图显示出来以后，点击‘发送’;\n更多功能敬请期待！/::,@";
	} else if (strstr ( $keyword, "1" ) || strstr ( $keyword, "绑定" )) {
		$content = "<a href=\"http://8.formtest1.sinaapp.com/callback1.php\">绑定通知书</a>";
	} else if (strstr ( $keyword, "2" ) || strstr ( $keyword, "个人信息" )) {
		$content = "<a href=\"http://8.formtest1.sinaapp.com/callback2.php\">个人信息</a>";
	} else if (strstr ( $keyword, "附近" )) {
		$locat = $object->FromUserName;
		$location = $mem->get ( $locat, $Arrayxy );
		if (! empty ( $location )) {
			$query = substr ( $object->Content, 6 );
			$arr1 = array (
					"query" => $query 
			);
			array_splice ( $location, 2, 1, $arr1 ); // array_splice选择数组中的一系列元素，但不返回，而是删除它们并用其它值代替
			$arr2 = $mem->set ( $locat, $location, 0, 600 );
			$url = "http://api.map.baidu.com/place/v2/search?ak=j8ywPTMtTmYACru9r20R4tVb&output=json&query={$query}&page_size=5&page_num=0&scope=2&location={$location['lng']},{$location['lat']}&radius=2000&filter=sort_name:distance";
			$r = file_get_contents ( $url );
			$l = json_decode ( $r );
			$title [] = array (
					"Title" => "附近的【" . $query . "】如下：",
					"Description" => "this is a test",
					"PicUrl" => "http://8.formtest1.sinaapp.com/img/xiaoyuandaohang.jpg",
					"Url" => "http://8.formtest1.sinaapp.com/callback3.php" 
			);
			for($i=0;$i<count($l->results);$i++){
			   $search [] = array (
					"Title" => $l->results[$i]->name."\n".$l->results[$i]->address."\n距离约：".$l->results[$i]->detail_info->distance."米",
					"Description" => "",
					"Url" => "http://api.map.baidu.com/direction?origin=latlng:{$location['lng']},{$location['lat']}|name:我的位置&destination={$l->results[$i]->location->lat},{$l->results[$i]->location->lng}&mode=walking&region=武汉&output=html&src=yourCompanyName|yourAppName" 
			   );
			}
		$content = array_merge_recursive($title,$search);   //数组合并
		} else {
			$content = "请重新发送您的位置。缓存之后发送“附近”加目标的命令，如“附近酒店”，“附近银行”。";
		}
		$mem->close;
	} else {
		$link = mysqli_connect ( SAE_MYSQL_HOST_M . ':' . SAE_MYSQL_PORT, SAE_MYSQL_USER, SAE_MYSQL_PASS );
		mysqli_select_db ( $link, "app_formtest1" );
		$FromUserName = $object->FromUserName;
		$Content = $object->Content;
		// $Time = $object->CreateTime;
		
		$AddTime = date ( 'y-m-d h:i:s', time () );
		// 拼装添加sql语句
		$sql = "insert into wx_message values(null,'$FromUserName','$Content','$AddTime')";
		// 执行添加操作
		mysqli_query ( $link, $sql );
		$content = $this->ichat ( $keyword );
	}
	
	if (is_array ( $content )) {
		if (isset ( $content [0] )) {
			$result = $this->transmitNews ( $object, $content );
		} else if (isset ( $content ['MusicUrl'] )) {
			$result = $this->transmitMusic ( $object, $content );
		}
	} else {
		$result = $this->transmitText ( $object, $content );
	}
	return $result;
}

// 接收图片消息
private function receiveImage($object) {
    /*$content = array (
			"MediaId" => $object->MediaId 
	);*/
    $pic = $object->PicUrl;
    $content = face($pic);
    //$result = $this->transmitImage ( $object, $content );
	$result = $this->transmitText ($object,$content);
	return $result;
}

// 接收位置消息
private function receiveLocation($object) {
	$mem = memcache_init ();
	// 获取地理位置消息的内容
	$locationArr = array (
			"Location_X" => $object->Location_X,
			"Location_Y" => $object->Location_Y,
			"Label" => $object->Label 
	);
	$lat = $object->Location_X; // 纬度
	$lng = $object->Location_Y; // 经度
	$q = "http://api.map.baidu.com/geoconv/v1/?coords={$lng},{$lat}&from=1&to=5&ak=j8ywPTMtTmYACru9r20R4tVb";
	$result = json_decode ( file_get_contents ( $q ) );
	// echo replyText($obj, "转换前".$obj->Location_X."\n"."转换前".$obj->Location_Y."\n"."转换后".$result->result[0]->x."\n"."转换后".$result->result[0]->y);
	$Arrayxy = array (
			"lat" => $result->result [0]->x,
			"lng" => $result->result [0]->y,
			"query" => "位置" 
	);
	$locat = $object->FromUserName;
	$mem->set ( $locat, $Arrayxy, 0, 600 );
	$content = "您的位置已缓存。\n现在可发送“附近”加目标的命令，如“附近酒店”，“附近加油站”。";
	$result = $this->transmitText ( $object, $content );
	return $result;
	$mem->close;
}

// 接收语音消息
private function receiveVoice($object) {
	if (isset ( $object->Recognition ) && ! empty ( $object->Recognition )) {
		$content = "你刚才说的是：" . $object->Recognition;
		$result = $this->transmitText ( $object, $content );
	} else {
		$content = array (
				"MediaId" => $object->MediaId 
		);
		$result = $this->transmitVoice ( $object, $content );
	}
	return $result;
}

// 接收视频消息
private function receiveVideo($object) {
	$content = array (
			"MediaId" => $object->MediaId,
			"ThumbMediaId" => $object->ThumbMediaId,
			"Title" => "",
			"Description" => "" 
	);
	$result = $this->transmitVideo ( $object, $content );
	return $result;
}

// 接收链接消息
private function receiveLink($object) {
	$content = "你发送的是链接，标题为：" . $object->Title . "；内容为：" . $object->Description . "；链接地址为：" . $object->Url;
	$result = $this->transmitText ( $object, $content );
	return $result;
}

// 回复文本消息
private function transmitText($object, $content) {
	if (! isset ( $content ) || empty ( $content )) {
		return "";
	}
	
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time (), $content );
	
	return $result;
}

// 回复图文消息
private function transmitNews($object, $newsArray) {
	if (! is_array ( $newsArray )) {
		return "";
	}
	$itemTpl = "        <item>
		<Title><![CDATA[%s]]></Title>
		<Description><![CDATA[%s]]></Description>
		<PicUrl><![CDATA[%s]]></PicUrl>
		<Url><![CDATA[%s]]></Url>
	</item>
";
	$item_str = "";
	foreach ( $newsArray as $item ) {
		$item_str .= sprintf ( $itemTpl, $item ['Title'], $item ['Description'], $item ['PicUrl'], $item ['Url'] );
	}
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[news]]></MsgType>
<ArticleCount>%s</ArticleCount>
<Articles>
$item_str    </Articles>
</xml>";
	
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time (), count ( $newsArray ) );
	return $result;
}

// 回复音乐消息
private function transmitMusic($object, $musicArray) {
	if (! is_array ( $musicArray )) {
		return "";
	}
	$itemTpl = "<Music>
	<Title><![CDATA[%s]]></Title>
	<Description><![CDATA[%s]]></Description>
	<MusicUrl><![CDATA[%s]]></MusicUrl>
	<HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
</Music>";
	
	$item_str = sprintf ( $itemTpl, $musicArray ['Title'], $musicArray ['Description'], $musicArray ['MusicUrl'], $musicArray ['HQMusicUrl'] );
	
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[music]]></MsgType>
$item_str
</xml>";
	
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time () );
	return $result;
}

// 回复图片消息
private function transmitImage($object, $imageArray) {
	$itemTpl = "<Image>
	<MediaId><![CDATA[%s]]></MediaId>
</Image>";
	
	$item_str = sprintf ( $itemTpl, $imageArray ['MediaId'] );
	
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[image]]></MsgType>
$item_str
</xml>";
	
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time () );
	return $result;
}

// 回复语音消息
private function transmitVoice($object, $voiceArray) {
	$itemTpl = "<Voice>
	<MediaId><![CDATA[%s]]></MediaId>
</Voice>";
	
	$item_str = sprintf ( $itemTpl, $voiceArray ['MediaId'] );
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
$item_str
</xml>";
	
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time () );
	return $result;
}

// 回复视频消息
private function transmitVideo($object, $videoArray) {
	$itemTpl = "<Video>
	<MediaId><![CDATA[%s]]></MediaId>
	<ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
	<Title><![CDATA[%s]]></Title>
	<Description><![CDATA[%s]]></Description>
</Video>";
	
	$item_str = sprintf ( $itemTpl, $videoArray ['MediaId'], $videoArray ['ThumbMediaId'], $videoArray ['Title'], $videoArray ['Description'] );
	
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[video]]></MsgType>
$item_str
</xml>";
	
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time () );
	return $result;
}

// 回复多客服消息
private function transmitService($object) {
	$xmlTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
	$result = sprintf ( $xmlTpl, $object->FromUserName, $object->ToUserName, time () );
	return $result;
}

// 回复第三方接口消息
private function relayPart3($url, $rawData) {
	$headers = array (
			"Content-Type: text/xml; charset=utf-8" 
	);
	$ch = curl_init ();
	curl_setopt ( $ch, CURLOPT_URL, $url );
	curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
	curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
	curl_setopt ( $ch, CURLOPT_POST, 1 );
	curl_setopt ( $ch, CURLOPT_POSTFIELDS, $rawData );
	$output = curl_exec ( $ch );
	curl_close ( $ch );
	return $output;
}

// 字节转Emoji表情
function bytes_to_emoji($cp) {
	if ($cp > 0x10000) { // 4 bytes
		return chr ( 0xF0 | (($cp & 0x1C0000) >> 18) ) . chr ( 0x80 | (($cp & 0x3F000) >> 12) ) . chr ( 0x80 | (($cp & 0xFC0) >> 6) ) . chr ( 0x80 | ($cp & 0x3F) );
	} else if ($cp > 0x800) { // 3 bytes
		return chr ( 0xE0 | (($cp & 0xF000) >> 12) ) . chr ( 0x80 | (($cp & 0xFC0) >> 6) ) . chr ( 0x80 | ($cp & 0x3F) );
	} else if ($cp > 0x80) { // 2 bytes
		return chr ( 0xC0 | (($cp & 0x7C0) >> 6) ) . chr ( 0x80 | ($cp & 0x3F) );
	} else { // 1 byte
		return chr ( $cp );
	}
}

// 日志记录
private function logger($log_content) {
	if (isset ( $_SERVER ['HTTP_APPNAME'] )) { // SAE
		sae_set_display_errors ( false );
		sae_debug ( $log_content );
		sae_set_display_errors ( true );
	} else if ($_SERVER ['REMOTE_ADDR'] != "127.0.0.1") { // LOCAL
		$max_size = 1000000;
		$log_filename = "log.xml";
		if (file_exists ( $log_filename ) and (abs ( filesize ( $log_filename ) ) > $max_size)) {
			unlink ( $log_filename );
		}
		file_put_contents ( $log_filename, date ( 'Y-m-d H:i:s' ) . " " . $log_content . "\r\n", FILE_APPEND );
	}
}
//智能聊天机器人
private function ichat($keyword) {
	$key = "76519f667e19c49d93d534a3ec415d7d";
	$url = "http://www.tuling123.com/openapi/api?key={$key}&info=" . $keyword;
	$curl = curl_init ();
	curl_setopt ( $curl, CURLOPT_URL, $url );
	curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, FALSE );
	curl_setopt ( $curl, CURLOPT_SSL_VERIFYHOST, FALSE );
	if (! empty ( $data )) {
		curl_setopt ( $curl, CURLOPT_POST, 1 );
		curl_setopt ( $curl, CURLOPT_POSTFIELDS, $data );
	}
	curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, 1 );
	$output = curl_exec ( $curl );
	curl_close ( $curl );
	
	$message = json_decode ( $output, true );
	$response = $message ['text'];
	
	// 防止机器人服务器异常回复自定义消息
	if (! empty ( $response )) {
		return $response;
	} else {
		$ran = rand ( 1, 5 );
		switch ($ran) {
			case 1 :
				return "胡巴今天累了，明天再陪你聊天吧。";
				break;
			case 2 :
				return "胡巴睡觉喽~~";
				break;
			case 3 :
				return "呼呼~~呼呼~~";
				break;
			case 4 :
				return "你话好多啊，不跟你聊了";
				break;
			case 5 :
				return "感谢您关注【武纺新生助手】";
				break;
			default :
				return "感谢您关注【武纺新生助手】";
				break;
		}
	}
}
}
// 调用人脸识别的API返回识别结果 
function face($imgUrl) 
{ 
  // face++ 链接 
  $jsonStr = 
    file_get_contents("http://apicn.faceplusplus.com/v2/detection/detect?url=".$imgUrl."&api_key=c3690a22d83ae4dfc84e5b03a472444f&api_secret=UrqUuBsODzcr81Qjf8Am6oDoQSPk_H_p&&attribute=glass,pose,gender,age,race,smiling"); 
  $replyDic = json_decode($jsonStr); 
  $resultStr = ""; 
  $faceArray = $replyDic->{'face'}; 
  $resultStr .= "图中共检测到".count($faceArray)."张脸！\n"; 
  for ($i= 0;$i< count($faceArray); $i++){ 
    $resultStr .= "第".($i+1)."张脸\n"; 
    $tempFace = $faceArray[$i]; 
    // 获取所有属性 
    $tempAttr = $tempFace->{'attribute'}; 
    // 年龄：包含年龄分析结果 
    // value的值为一个非负整数表示估计的年龄, range表示估计年龄的正负区间 
    $tempAge = $tempAttr->{'age'}; 
    // 性别：包含性别分析结果 
    // value的值为Male/Female, confidence表示置信度 
    $tempGenger = $tempAttr->{'gender'};  
    // 种族：包含人种分析结果 
    // value的值为Asian/White/Black, confidence表示置信度 
    $tempRace = $tempAttr->{'race'};    
    // 微笑：包含微笑程度分析结果 
    //value的值为0-100的实数，越大表示微笑程度越高 
    $tempSmiling = $tempAttr->{'smiling'}; 
    // 眼镜：包含眼镜佩戴分析结果 
    // value的值为None/Dark/Normal, confidence表示置信度 
    $tempGlass = $tempAttr->{'glass'};   
    // 造型：包含脸部姿势分析结果 
    // 包括pitch_angle, roll_angle, yaw_angle 
    // 分别对应抬头，旋转（平面旋转），摇头 
    // 单位为角度。 
    $tempPose = $tempAttr->{'pose'}; 
    //返回年龄 
    $minAge = $tempAge->{'value'} - $tempAge->{'range'}; 
    $minAge = $minAge < 0 ? 0 : $minAge; 
    $maxAge = $tempAge->{'value'} + $tempAge->{'range'}; 
    $resultStr .= "年龄：".$minAge."-".$maxAge."岁\n"; 
    // 返回性别 
    if($tempGenger->{'value'} === "Male") 
      $resultStr .= "性别：男\n";  
    else if($tempGenger->{'value'} === "Female") 
      $resultStr .= "性别：女\n"; 
    // 返回种族 
    if($tempRace->{'value'} === "Asian") 
      $resultStr .= "种族：黄种人\n";   
    else if($tempRace->{'value'} === "Male") 
      $resultStr .= "种族：白种人\n";   
    else if($tempRace->{'value'} === "Black") 
      $resultStr .= "种族：黑种人\n";   
    // 返回眼镜 
    if($tempGlass->{'value'} === "None") 
      $resultStr .= "眼镜：木有眼镜\n";  
    else if($tempGlass->{'value'} === "Dark") 
      $resultStr .= "眼镜：目测墨镜\n";  
    else if($tempGlass->{'value'} === "Normal") 
      $resultStr .= "眼镜：普通眼镜\n";  
    //返回微笑 
    $resultStr .= "微笑：".round($tempSmiling->{'value'})."%\n"; 
  }   
  if(count($faceArray) === 2){ 
    // 获取face_id 
    $tempFace = $faceArray[0]; 
    $tempId1 = $tempFace->{'face_id'}; 
    $tempFace = $faceArray[1]; 
    $tempId2 = $tempFace->{'face_id'}; 
  
    // face++ 链接 
    $jsonStr = 
      file_get_contents("https://apicn.faceplusplus.com/v2/recognition/compare?api_secret=ViX19uvxkT_A0a6d55Hb0Q0QGMTqZ95f&api_key=5eb2c984ad24ffc08c352bdb53ee52f8&face_id2=".$tempId2 ."&face_id1=".$tempId1); 
    $replyDic = json_decode($jsonStr); 
    //取出相似程度 
    $tempResult = $replyDic->{'similarity'}; 
    $resultStr .= "相似程度：".round($tempResult)."%\n"; 
    //具体分析相似处 
    $tempSimilarity = $replyDic->{'component_similarity'}; 
    $tempEye = $tempSimilarity->{'eye'}; 
    $tempEyebrow = $tempSimilarity->{'eyebrow'}; 
    $tempMouth = $tempSimilarity->{'mouth'}; 
    $tempNose = $tempSimilarity->{'nose'}; 
    $resultStr .= "相似分析：\n"; 
    $resultStr .= "眼睛：".round($tempEye)."%\n"; 
    $resultStr .= "眉毛：".round($tempEyebrow)."%\n"; 
    $resultStr .= "嘴巴：".round($tempMouth)."%\n"; 
    $resultStr .= "鼻子：".round($tempNose)."%\n"; 
  } 
  
  //如果没有检测到人脸 
  if($resultStr === "") 
    $resultStr = "照片中木有人脸=.="; 
  return $resultStr; 
}; 
?>